const $ = el => document.querySelector(el)
const gets = el => [...document.querySelectorAll(el)]

// 2.	使用promise封装xhr请求
function xhrFn(method,url){
    return new Promise((resolve,reject) =>{
        const xhr = new XMLHttpRequest()
        xhr.open(method,url,false)
        xhr.onreadystatechange = ()=>{
            if(xhr.readyState === 4){
                if(xhr.status === 200){
                    let datas = JSON.parse(xhr.responseText)
                    resolve(datas)
                }
            }else{
                reject(xhr.status)
            }
        }
        xhr.send()
    })
}
// 渲染title内容
xhrFn('get','http://zyxcl.xyz/exam_api/food')
.then(datas =>{
    let history = JSON.parse(sessionStorage.getItem('history')),
        data = [],
        curIndex = 0,
        dataAll = [],
        titles = ['以下食物升糖指数较高，建议少量食用','以下食物升糖指数适中，建议适量食用','以下食物升糖指数偏低，可以放心使用食用'],
        color = ['red','#ea8e00','#66bb6a']
    history.forEach(item =>{
        datas.value.forEach(it =>{
            it.list.forEach(it1 =>{
                if(it1.name === item) data.push(it1)
            })
        })
    })
    dataAll.push(
        data.filter(item =>{
            return item.glycemicIndex >70 && item.glycemicIndex <= 100
        }),
        data.filter(item =>{
            return  item.glycemicIndex <= 70 && item.glycemicIndex >40
        }),
        data.filter(item =>{
            return item.glycemicIndex <= 40
        })
    )
    console.log(dataAll)
    gets('.tit span').forEach((span,i)=>{
        span.innerHTML = dataAll[i].length
    })
    render()
    // tit点击事件
    gets('.tit div').forEach((div,i)=>{
        div.addEventListener('click',()=>{
            $('.black').classList.remove('black')
            curIndex = i
            gets('.tit div')[curIndex].classList.add('black')
            render()
        })
    })
    //    封装渲染内容函数
    function render(){
        $('h3').innerHTML = titles[curIndex]
        $('h3').style.color = color[curIndex]
        $('ul').innerHTML = dataAll[curIndex].map(item=>{
            return ` <li>
                   <div class="title">
                    <div>
                        <img src="${item.imgUrl}" alt="">
                        <h4>${item.name}</h4>
                    </div>
                    <p>升糖指数：${item.glycemicIndex}</p>
                   </div>
                    <p>${item.content}</p>
                </li>`
        }).join('')
    }
})
.catch(error =>{
    console.log('请求失败：' + error)
})